package com.keta.foundation.controller;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.keta.foundation.util.dwz.AjaxObject;
import com.keta.foundation.util.dwz.Page;
import com.keta.generator.SimpleModuleGenerator;
import com.keta.generator.db.DataSource;
import com.keta.generator.db.DbFactory;
import com.keta.generator.util.ConvertHandler;
import com.keta.generator.vo.Column;
import com.keta.generator.vo.Table;

@Controller
@RequestMapping("/online_gen")
public class OnlineGenController {
	
	private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

	private static final String ONLINEGEN_LIST = "onlineGen/list";
	private static final String ONLINEGEN_CUSTOM = "onlineGen/custom";
	
	private final  String[]  SYSTEM_TABLES = new String[]{"t_dict","t_file_resource","t_log_info","t_module",
			"t_organization","t_organization_role","t_permission","t_role","t_role_permission","t_user","t_user_role"};
	
	@RequiresPermissions("OnlineGen:view")
	@RequestMapping("/list")
	public String list(ServletRequest request, Page page, Model model,String name){
		
		try {
			DataSource dataSource =  DbFactory.getDataSource();
			List<Table> tables=  dataSource.getTables();
			
			List<Table> userTables = new ArrayList<>();
			
			
			for(Table table : tables){
			  if(!isSystemTable(table.getTableName())){
				  
				Properties pops = new Properties();
				pops.load(OnlineGenController.class.getResourceAsStream("/generator/simple_module_gen.properties"));
				String  tablePrefix = pops.getProperty("table.prefix");
				//将表前缀替换为空
				String tableName = table.getTableName();
				tableName = tableName.replace(tablePrefix, "");
				String javaBean = ConvertHandler.table2EntityName(tableName);
				table.setEntityName(javaBean);
				String instace = Character.toLowerCase(javaBean.charAt(0)) + javaBean.substring(1);
				table.setInstanceName(instace);
				
				
				if(StringUtils.isNotBlank(name)){
					if(table.getTableName().contains(name) || table.getTableName().equals(name)){
						userTables.add(table);	
					}
				}else{
					userTables.add(table);	
				}
				
				
			  }
			}
			model.addAttribute("name", name);
			model.addAttribute("tables", userTables);
		} catch (Exception e) {
			e.printStackTrace();
		}
		model.addAttribute("page", page);
		return ONLINEGEN_LIST;
	}
	
	
	
	private boolean isSystemTable(String tableName){
		for(String sysTable : SYSTEM_TABLES){
			if(tableName.equals(sysTable)){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 默认生成
	 */
	@RequiresPermissions("OnlineGen:gen")
	@RequestMapping("/gen/{tableName}")
	public @ResponseBody String gen(@PathVariable String tableName){
		try {
			SimpleModuleGenerator gen = new SimpleModuleGenerator();
			gen.gen(tableName);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxObject.newOk("代码生成失败，请检查！").toString();
		}
		logger.debug(tableName + "生成成功");
		return AjaxObject.newOk("代码生成成功！").setCallbackType("").toString();
	}
	
	
	@RequiresPermissions("OnlineGen:custome")
	@RequestMapping(value="/custom/{tableName}",method = RequestMethod.GET)
	public  String preCustomGen(@PathVariable String tableName,Model model){
		
		Properties pops = new Properties();
		try {
			pops.load(OnlineGenController.class.getResourceAsStream("/generator/simple_module_gen.properties"));
			String packageName= pops.getProperty("package.name");
			String templatePath = pops.getProperty("template.path");
			String tablePrefix = pops.getProperty("table.prefix");
			String projectPath = pops.getProperty("project.path");
			
			model.addAttribute("packageName", packageName);
			model.addAttribute("templatePath", templatePath);
			model.addAttribute("tablePrefix", tablePrefix);
			model.addAttribute("projectPath", projectPath);
			model.addAttribute("tableName", tableName);
			
			tableName = tableName.replace(tablePrefix, "");
			String entityName = ConvertHandler.table2EntityName(tableName);
			String instanceName = Character.toLowerCase(entityName.charAt(0)) + entityName.substring(1);
			
			model.addAttribute("entityName", entityName);
			model.addAttribute("instanceName", instanceName);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return ONLINEGEN_CUSTOM;
	}
	
	/**
	 * 自定义生成，可以设置生成的各项参数
	 */
	@RequiresPermissions("OnlineGen:custome")
	@RequestMapping(value="/custom",method = RequestMethod.POST)
	public @ResponseBody  String customGen(String tableName,String packageName,String projectPath,
			String tablePrefix,String requestMapping,String entityName,
			String instanceName,String moduleName){
		
		try {
			SimpleModuleGenerator generator = new SimpleModuleGenerator();
			
			if(StringUtils.isNotBlank(packageName)){
				generator.setPackageName(packageName);
			}
			if(StringUtils.isNotBlank(projectPath)){
				generator.setProjectPath(projectPath);
			}
			if(StringUtils.isNotBlank(tablePrefix)){
				generator.setTablePrefix(tablePrefix);
			}
			if(StringUtils.isNotBlank(requestMapping)){
				generator.setRequestMapping(requestMapping);
			}
			if(StringUtils.isNotBlank(entityName)){
				generator.setEntityName(entityName);
			}
			if(StringUtils.isNotBlank(instanceName)){
				generator.setInstanceName(instanceName);
			}
			if(StringUtils.isNotBlank(moduleName)){
				generator.setModuleName(moduleName);
			}
			
			generator.gen(tableName);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return AjaxObject.newOk("代码生成成功！").setCallbackType("").toString();
	}
}
